//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package dao

import (
	"context"
	"regexp"

	"atomgit.com/openlinksaas/api-server/dao/db_ns"
	"atomgit.com/openlinksaas/proto-gen-go.git/keyword_api"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type KeywordDbItem struct {
	Keyword   string `bson:"_id"`
	TimeStamp int64  `bson:"timeStamp"`
}

func (item *KeywordDbItem) ToKeywordInfo() *keyword_api.KeywordInfo {
	return &keyword_api.KeywordInfo{
		Keyword:   item.Keyword,
		TimeStamp: item.TimeStamp,
	}
}

type _KeywordDao struct {
	mc *mongo.Collection
}

func newKeywordDao(db *mongo.Database) (*_KeywordDao, error) {
	mc := db.Collection(db_ns.DB_NS_GLOBAL + "keyword")
	_, err := mc.Indexes().CreateOne(context.Background(), mongo.IndexModel{
		Keys: bson.D{{"timeStamp", 1}},
	})
	if err != nil {
		return nil, err
	}
	return &_KeywordDao{mc: mc}, nil
}

func (db *_KeywordDao) Insert(ctx context.Context, dbItem *KeywordDbItem) error {
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_KeywordDao) Exist(ctx context.Context, keyword string) (bool, error) {
	count, err := db.mc.CountDocuments(ctx, bson.M{"_id": keyword})
	return count > 0, err
}

func (db *_KeywordDao) Remove(ctx context.Context, keyword string) error {
	_, err := db.mc.DeleteOne(ctx, bson.M{"_id": keyword})
	return err
}

func (db *_KeywordDao) Count(ctx context.Context, filterBySearchStr bool, searchStr string) (uint32, error) {
	query := bson.M{}
	if filterBySearchStr {
		query["_id"] = primitive.Regex{
			Pattern: regexp.QuoteMeta(searchStr),
			Options: "i",
		}
	}
	count, err := db.mc.CountDocuments(ctx, query)
	return uint32(count), err
}

func (db *_KeywordDao) List(ctx context.Context, filterBySearchStr bool, searchStr string, offset, limit int64) ([]*KeywordDbItem, error) {
	query := bson.M{}
	if filterBySearchStr {
		query["_id"] = primitive.Regex{
			Pattern: regexp.QuoteMeta(searchStr),
			Options: "i",
		}
	}
	cursor, err := db.mc.Find(ctx, query, options.Find().SetSkip(offset).SetLimit(limit).SetSort(bson.D{{"timeStamp", -1}, {"_id", -1}}))
	if err != nil {
		return nil, err
	}
	retList := []*KeywordDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}

func (db *_KeywordDao) DistinctKeyword(ctx context.Context) ([]string, error) {
	itemList, err := db.mc.Distinct(ctx, "_id", bson.M{})
	if err != nil {
		return nil, err
	}
	retList := []string{}
	for _, item := range itemList {
		retList = append(retList, item.(string))
	}
	return retList, nil
}
